#include <stdio.h>
#include <sys/types.h>
#include <assert.h>
#include "logger.h"
#include "trunk.h"


int* newIntArray(int begin, int step, int size, mrr_phypos *pos) {

	int* testdata;
	int* intp;
	int num;
	int i;
	int cap;

	cap = sizeof(int) * size;
	testdata = malloc(cap);
	intp = testdata;
	num = begin;
	for (i = 0; i< size; i++) {

		*intp = num;

		intp++;
		num += step;
	}

	mrr_trunk_write(testdata, cap, pos);

	return testdata;
}

int main(void) {

	mrr_phypos *pos;
	mrr_phypos **poslist;
	mrr_phypos **posp;
	int **idatap;
	int **idata;
	size_t testsize = 10;

	pos = mrr_phypos_new();

	idata = (int**) malloc(sizeof(int*) * testsize);
	poslist = (mrr_phypos**)malloc(sizeof(mrr_phypos*) * testsize);

	idatap = idata;
	posp = poslist;
	*posp = mrr_phypos_clone(pos);
	*idatap = newIntArray(0, 1, 200, *posp);
	idatap++;
	posp++;

	mrr_phypos_shift31(pos, TRUNK_SIZE - 50);
	*posp = mrr_phypos_clone(pos);
	*idatap = newIntArray(10000, 1, 200, *posp);
	idatap++;
	posp++;

	mrr_phypos_shift31(pos, 2 * TRUNK_SIZE - 150);
	*posp = mrr_phypos_clone(pos);
	*idatap = newIntArray(20000, 1, 200, *posp);
	idatap++;
	posp++;

	*idatap = NULL;
	*posp = NULL;


	mrr_debug("check reading...", "");
	for (idatap = idata, posp = poslist; *idatap != NULL; idatap++, posp++) {

		int* stored;
		stored = malloc(sizeof(int)*200);

		mrr_trunk_read(stored, sizeof(int)*200, *posp);

		int i = 200 - 1;
		int *d0, *d1;
		d0 = *idatap;
		d1 = stored;
		
		for (; i>=0; i --) {
			
			assert(*d0 == *d1);
			d0++;
			d1++;
		}
	}

	// free all resources
	for (idatap = idata, posp = poslist; *idatap != NULL; idatap++, posp++) {
		free(*idatap);
		mrr_phypos_free(*posp);
	}

	mrr_phypos_free(pos);

	return 0;
}
